package com.qms.tubu.widget;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;

import com.qms.tubu.adapter.CycleFragmentAdapter;

/**
 * Created by Mad on 2015/7/3.
 */
public class AutoCycleViewPager extends ViewPager{
    private CycleRadioGroup mRadioGroup;
    private int pageNum;
    public AutoCycleViewPager(Context context) {
        super(context);
        addOnPageChangeListener(mListener);
    }

    public AutoCycleViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        addOnPageChangeListener(mListener);
    }
    public void setGroup(CycleRadioGroup radioGroup)
    {
        mRadioGroup=radioGroup;
    }
    private OnPageChangeListener mListener=new OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if(mRadioGroup!=null)
            {
                mRadioGroup.check(position%pageNum);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            removeCallbacks(autoRun);
            if(state==ViewPager.SCROLL_STATE_IDLE)
            {
                postDelayed(autoRun,5000);
            }
        }
    };


    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
        removeCallbacks(autoRun);
        if(adapter==null)
            return;
        if(adapter instanceof CycleFragmentAdapter)
        {
            CycleFragmentAdapter cycleAdapter= (CycleFragmentAdapter) adapter;
            pageNum=cycleAdapter.getList().size();

            if(mRadioGroup!=null)
            {
                mRadioGroup.updateChild(pageNum);
                mRadioGroup.check(0);
            }
            if(pageNum<=1)
                return;
            this.setCurrentItem(1000*pageNum,false);

            postDelayed(autoRun,5000);
        }
    }

    private Runnable autoRun=new Runnable() {
        @Override
        public void run() {
            int position=getCurrentItem();
            setCurrentItem(position+1,true);
        }
    };
}
